package com.lyw.wechatkf.service;

import com.alibaba.fastjson.JSON;
import com.lyw.wechatkf.entity.MessageResult;
import com.lyw.wechatkf.entity.MessageSend;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@Service
public class MessageService {

//    @Autowired
//    RestTemplate restTemplate;

    /**
     * demo 先返回一个messageResult
     * @param cursor
     * @param token
     * @param limit
     * @param voice_format
     * @param access_token
     * @return
     * @throws IOException
     */
    public MessageResult getMessage(String cursor, String token, Integer limit, Integer voice_format, String access_token) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("cursor", cursor);
        map.put("token", token);
        if (limit != null){
            map.put("limit", limit);
        }
        if (voice_format != null){
            map.put("voice_format", voice_format);
        }
        Content content = Request.Post("https://qyapi.weixin.qq.com/cgi-bin/kf/sync_msg?access_token=" + access_token)
                .bodyString(JSON.toJSONString(map), ContentType.APPLICATION_JSON).execute().returnContent();
        String x = content.asString(StandardCharsets.UTF_8);
//        System.out.println(x);
        MessageResult messageResult = JSON.parseObject(x, MessageResult.class);
        return messageResult;
    }

    public void sendMessage(MessageSend messageSend, String access_token) throws IOException {
        Content content = Request.Post("https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg?access_token=" + access_token)
                .bodyString(JSON.toJSONString(messageSend), ContentType.APPLICATION_JSON).execute().returnContent();
        System.out.println("发送消息后结果:"+content.asString(StandardCharsets.UTF_8));
    }
}
